package com.cnlxu.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.support.v4.widget.DrawerLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cnlxu.data.StickerAdapter;
import com.cnlxu.data.StickerModel;
import com.cnlxu.data.LeftMenuAdapter;
import com.cnlxu.data.LeftMenuModel;
import com.cnlxu.data.StickerView;
import com.cnlxu.database.DBManager;
import com.cnlxu.database.WordInfo;
import com.cnlxu.network.HttpProxy;
import com.example.cninlaxu.curltest.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cnlxu on 2016/8/9.
 */
public class MainPage extends Activity{

    private ListView listView;
    private ArrayList<LeftMenuModel> list;
    private ArrayList<StickerModel> stickerModels;
    private ImageView leftMenu;
    private DrawerLayout drawerLayout;
    private StickerAdapter stickerAdapter;
    private LeftMenuAdapter leftMenuAdapter;
    private ListView cv;
    private DBManager dbManager=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        //getActionBar().hide();
        drawerLayout = (DrawerLayout)findViewById(R.id.m_lyt);
      /*  leftMenu = (ImageView) findViewById(R.id.leftmenu);
        leftMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });*/

        initData();
        // sticker view
        stickerAdapter = new StickerAdapter(this, stickerModels);
        cv = createSticker(stickerAdapter);
        int width= TileLayout.LayoutParams.MATCH_PARENT;
        int height = TileLayout.LayoutParams.WRAP_CONTENT;
        cv.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        TileLayout llContent1 = (TileLayout)findViewById(R.id.tl_content1);
        llContent1.addView(cv);
        //cv = (ListView) findViewById(R.id.clv_words);


        ImageButton ibSearch = (ImageButton)findViewById(R.id.ib_search);
        ibSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = (EditText)findViewById(R.id.et_input);
                onQuery(et.getText().toString());
                et.clearFocus();
            }
        });
        ///
        listView = (ListView) findViewById(R.id.left_listview);
        leftMenuAdapter = new LeftMenuAdapter(this, list);
        listView.setAdapter(leftMenuAdapter);
      /*  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                FragmentTransaction bt = fm.beginTransaction();
                switch ((int) id) {
                    case 1:
                        bt.replace(R.id.content, new NewsFragment());
                        break;
                    case 2:
                        bt.replace(R.id.content, new SubscriptionFragment());
                        break;

                    default:
                        break;
                }
                bt.commit();
                drawerLayout.closeDrawer(Gravity.LEFT);
            }
        });*/
    }

    private StickerView createSticker(StickerAdapter stickerAdapter){
        StickerView cv = new StickerView(this);
        cv.setAdapter(stickerAdapter);
        cv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WordInfo wordInfo = dbManager.queryById((int)id);
                Bundle b = new Bundle();
                b.putString("word", wordInfo.name);
                b.putString("result", wordInfo.translation);
                showResult(b);
               // Toast.makeText(MainPage.this,"id "+String.valueOf(id),Toast.LENGTH_LONG).show();
            }
        });
        return cv;
    }

    ///
    private void initData() {

        dbManager = new DBManager(this);
        //
        list = new ArrayList<LeftMenuModel>();
        list.add(new LeftMenuModel(R.drawable.arrow, "新闻", 1));
        list.add(new LeftMenuModel(R.drawable.arrow, "订阅", 2));
        list.add(new LeftMenuModel(R.drawable.arrow, "图片", 3));
        list.add(new LeftMenuModel(R.drawable.arrow, "视频", 4));
        list.add(new LeftMenuModel(R.drawable.arrow, "跟帖", 5));
        list.add(new LeftMenuModel(R.drawable.arrow, "投票", 6));
        //
        stickerModels = new ArrayList<StickerModel>();

        ArrayList<WordInfo> wordInfos = dbManager.queryByWeek(1);
        for(WordInfo wordInfo:wordInfos){
            stickerModels.add(new StickerModel(wordInfo._id,
                                                        wordInfo.week,
                                                        wordInfo.counter,
                                                        wordInfo.name,
                                                        wordInfo.status));
        }
    }

    //
    private ArrayList<Map<String,String>> getListData(){
        ArrayList<Map<String,String>> listData = new ArrayList<Map<String,String>>();

        Map<String,String> map = new HashMap<String, String>();
        map.put("text", "分享");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "检查新版本");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "反馈意见");
        listData.add(map);

        map = new HashMap<String, String>();
        map.put("text", "关于我们");
        listData.add(map);
        return listData;
    }
    private void showResult(Bundle bundle){
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.trans_dlg, (ViewGroup) findViewById(R.id.llayout_dlg));
        TextView tv = (TextView)layout.findViewById(R.id.tv_trans_result);
        final String result = bundle.getString("result");
        final String word = bundle.getString("word");
        tv.setText(result);
        new AlertDialog.Builder(this).setTitle(word).setView(layout)
                .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        WordInfo wordInfo = storeWord(word, result, "", "");
                        if (wordInfo._id != -1) {
                            stickerModels.add(new StickerModel(wordInfo));
                            stickerAdapter.notifyDataSetChanged();
                        }
                      //  Toast.makeText(MainPage.this, "On ok click:" + word + result, Toast.LENGTH_LONG).show();
                    }
                }).setNegativeButton("Cancel", null).show();
    }

    //
    private WordInfo getLocalWord(String word)
    {
        WordInfo info = dbManager.queryByName(word);
        return info;
    }

    //
    private WordInfo storeWord(String word, String tranlation,String details, String more)
    {
        return dbManager.add(word, tranlation, details, more);
    }
    //
    private Handler mProgressHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if(msg.what==1) {
              /*  tv.setText(msg.getData().getString("result"));
                Toast.makeText(MainActivity.this, msg.getData().getString("result"), Toast.LENGTH_SHORT).show();*/
                showResult(msg.getData());
            }
            super.handleMessage(msg);
        }
    };

    //
    private void onQuery(final String queryString){
        if(queryString.isEmpty()){
            return;
        }

        new Thread( new Runnable() {
            public void run() {
                Message msg=new Message();
                msg.what=1;
                Bundle b = new Bundle();
                //check it already exist
                WordInfo info =  getLocalWord(queryString);
                if(info._id == -1) {
                    HttpProxy p =new HttpProxy();
                    info.translation = p.translation(queryString);
                }
                b.putString("word", queryString);
                b.putString("result", info.translation);
                msg.setData(b);
                mProgressHandler.sendMessage(msg);
            }
        }).start();
    }

    ///*
    /*
    private boolean dragView(View v, MotionEvent event){

        int action=event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                lastX = (int)event.getRawX();
                lastY = (int)event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dx =(int)event.getRawX() - lastX;
                int dy =(int)event.getRawY() - lastY;

                left = v.getLeft() + dx;
                top = v.getTop() + dy;
                right = v.getRight() + dx;
                bottom = v.getBottom() + dy;
                if(left < 0){
                    left = 0;
                    right = left + v.getWidth();
                }
                if(right > screenWidth){
                    right = screenWidth;
                    left = right - v.getWidth();
                }
                if(top < 0){
                    top = 0;
                    bottom = top + v.getHeight();
                }
                if(bottom > screenHeight){
                    bottom = screenHeight;
                    top = bottom - v.getHeight();
                }
                v.layout(left, top, right, bottom);
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                break;
            default:
                break;
        }
        return true;
    }
     */
}
